import {useKeyPress} from "ahooks";
import {
  copySelectedComponent,
  deleteComponent,
  pasteComponent,
  selectNextComponent,
  selectPrevComponent
} from "../redux/componentsReducer";
import {useDispatch} from "react-redux";
import {ActionCreators as UndoActionCreators} from "redux-undo";

const isActiveElementValid = () => {
  const activeElement = document.activeElement
  // // 所有的非输入类dom，返回的activeElement都为document.body  增加dnd-kit之前
  // return activeElement === document.body;
  // 所有的非输入类dom，返回的activeElement都为document.body  增加dnd-kit之前
  if (activeElement === document.body) return true
  if (activeElement?.matches('div[role="button"]')) return true
  return false
}

function useBindCanvasKeyPress() {
  const dispatch = useDispatch()
  useKeyPress(['delete', 'backspace'], () => {
    if (isActiveElementValid()) {
      dispatch(deleteComponent())
    }
  })
  useKeyPress(['ctrl.c', 'meat.c'], () => {
    if (isActiveElementValid()) {
      dispatch(copySelectedComponent())
    }
  })
  useKeyPress(['ctrl.v', 'meat.v'], () => {
    if (isActiveElementValid()) {
      dispatch(pasteComponent())
    }
  })
  useKeyPress(['uparrow'], () => {
    if (isActiveElementValid()) {
      dispatch(selectPrevComponent())
    }
  })
  useKeyPress(['downarrow'], () => {
    if (isActiveElementValid()) {
      dispatch(selectNextComponent())
    }
  })
  useKeyPress(['ctrl.z', 'meta.z'], () => {
    if (isActiveElementValid()) {
      dispatch(UndoActionCreators.undo())
    }
  }, {
    exactMatch: true
  })
  useKeyPress(['ctrl.shift.z', 'meta.shift.z'], () => {
    if (isActiveElementValid()) {
      dispatch(UndoActionCreators.redo())
    }
  }, {
    exactMatch: true
  })
}

export default useBindCanvasKeyPress
